package cn.xinfei.xdecision.common.service.component.dependency;

import cn.xinfei.xdecision.common.model.component.dependency.EngineNodeComponentRel;
import cn.xinfei.xdecision.common.model.enginex.po.EngineNode;
import cn.xinfei.xdecision.common.utils.enums.enginex.NodeTypeEnum;
import cn.xinfei.xdecision.common.utils.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 依赖关系抽象类
 *
 * @author zdy
 * @since 20230404
 */
@Slf4j
public abstract class AbstractDependency {

    protected static final Map<String, AbstractDependency> map = new HashMap<>();

    public static Map<String, AbstractDependency> getAbstractDependencyMap() {
        return map;
    }

    /**
     * 准备数据
     *
     * @param nodeJson 引擎组件入参
     * @see NodeTypeEnum
     */
    protected abstract List<EngineNodeComponentRel> initData(final String nodeJson, final EngineNode engineNode);

    /**
     * 数据初始化
     */
    protected EngineNodeComponentRel initData(EngineNode engineNode) {
        EngineNodeComponentRel engineNodeComponentRel = new EngineNodeComponentRel();
        return engineNodeComponentRel
                .setEngineNodeId(engineNode.getId())
                .setEngineVersionId(engineNode.getVersionId())
                .setEngineNodeCode(engineNode.getNodeCode())
                .setEngineNodeName(engineNode.getNodeName())
                .setComponentType(NodeTypeEnum.adapad(engineNode.getNodeType()).getCode());
    }


    public Boolean saveOrUpdateDependency(EngineNode engineNode) {
        EngineNodeComponentRelService engineNodeComponentRelService = SpringContextUtil.getBean(EngineNodeComponentRelService.class);
        List<EngineNodeComponentRel> engineNodeComponentRelList = initData(engineNode.getNodeJson(), engineNode);
        //先删除原来的依赖关系，再新增新的依赖关系
        engineNodeComponentRelService.removeRel(engineNodeComponentRelList);
        for (EngineNodeComponentRel engineNodeComponentRel : engineNodeComponentRelList) {
            if (Boolean.FALSE.equals(engineNodeComponentRelService.saveOrUpdateRel(engineNodeComponentRel))) {
                log.error("依赖关系保存失败，参数===》{}", engineNodeComponentRel);
                return Boolean.FALSE;
            }
        }
        return Boolean.TRUE;
    }
}
